package com.wushi.lenovo.asia5b.app_utils.helper;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mvp.base.BaseAppCompatActivity;
import com.mvp.base.model.ResultModel;
import com.mvp.common.LocalManageUtil;
import com.mvp.dagger.modules.NetworkModule;
import com.mvp.helper.WCallBack;
import com.mvp.utils.JsonUtils;
import com.mvp.utils.ResString;
import com.mvp.utils.SharedPreferencesUtils;
import com.wushi.lenovo.asia5b.R;
import com.wushi.lenovo.asia5b.app_http.ApiService;
import com.wushi.lenovo.asia5b.app_http.TopupService;
import com.wushi.lenovo.asia5b.app_model.credit.CreditMinModel;
import com.wushi.lenovo.asia5b.app_model.good.OrderCancelModel;
import com.wushi.lenovo.asia5b.app_model.other.CacheType;
import com.wushi.lenovo.asia5b.app_model.other.CategoryModel;
import com.wushi.lenovo.asia5b.app_model.other.UserInfo;
import com.wushi.lenovo.asia5b.app_model.profile.CountryModel;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

import static timber.log.Timber.d;

/**
 * Created by zhangyuncai on 2019/4/10.
 * 针对各种缓存的帮助类
 */
public class CacheHelper {
    private static final String CREDITMIN = "CREDITMIN";
    private static final String COUNTRYS = "COUNTRYS";
    private final static String SEARCH_KEYWORD = "SEARCH_KEYWORD";//搜索词的历史记录
    private final static String CATEGORYS = "CATEGORYS";//左侧菜单栏
    private static List<OrderCancelModel> orderCancelModels;//取消订单的原因集合

    //-----------与国家相关-----------start
    //-----------与国家相关-----------start
    public static void getCountrys(WCallBack<List<CountryModel>> callBack, CacheType cacheType) {
        List<CountryModel> countryModels = loadCountrys();
        if (cacheType == CacheType.LOCAL) {
            if (countryModels != null) {
                if (callBack != null) {
                    callBack.callback(countryModels);
                }
            } else {
                getCountrysByNet(callBack);
            }
        } else if (cacheType == CacheType.NET) {
            getCountrysByNet(callBack);
        } else if (cacheType == CacheType.LOCAL_NET) {
            if (callBack != null) {
                callBack.callback(countryModels);
            }
            getCountrysByNet(callBack);
        }

    }

    private static void getCountrysByNet(WCallBack<List<CountryModel>> callBack) {
        ApiService apiService = NetworkModule.getRetrofit().create(ApiService.class);
        apiService.getCountrys()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(listResultModel -> {
                    if (listResultModel.isSuccess()) {
                        if (callBack != null) {
                            callBack.callback(listResultModel.getData());
                        }
                        saveCountrys(listResultModel.getData());
                    }
                }, throwable -> {
                    CrashHelper.postCatchedException(throwable);
                });

    }


    private static void saveCountrys(List<CountryModel> countryModels) {
        String gsonString = "";
        if (countryModels != null) {
            gsonString = JsonUtils.createGsonString(countryModels);
        }
        SharedPreferencesUtils.putData(COUNTRYS, gsonString);
    }

    private static List<CountryModel> loadCountrys() {
        List<CountryModel> countryModels = null;
        try {
            String s = (String) SharedPreferencesUtils.getData(COUNTRYS, "");
            Gson gson = new Gson();
            Type type = new TypeToken<List<CountryModel>>() {
            }.getType();
            countryModels = gson.fromJson(s, type);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return countryModels;
    }
    //-----------与国家相关-----------end
    //-----------与国家相关-----------end

    //-----------与充值额度相关-----------start
    //-----------与充值额度相关-----------start

    /**
     * @param callBack
     * @param cacheType
     * @return 返回的是本地缓存
     */
    public static CreditMinModel getCreditMin(WCallBack<CreditMinModel> callBack, CacheType cacheType) {
        //首先本地拿到缓存
        CreditMinModel model = null;
        int memberId = UserInfo.getMemberId();
        if (memberId > 0) {
            String key = CREDITMIN + "+" + memberId;
            String s = (String) SharedPreferencesUtils.getData(key, "");

            try {
                model = JsonUtils.changeGsonToBean(s, CreditMinModel.class);
            } catch (Exception e) {
                e.printStackTrace();
                model = null;
            }
        }

        if (cacheType == CacheType.LOCAL) {
            if (model != null) {
                if (callBack != null) {
                    callBack.callback(model);
                }
            } else {
                getCreditMinByNet(callBack);
            }
        } else if (cacheType == CacheType.NET) {
            getCreditMinByNet(callBack);
        } else if (cacheType == CacheType.LOCAL_NET) {
            if (callBack != null) {
                callBack.callback(model);
            }
            getCreditMinByNet(callBack);
        }


        if (model == null) {
            model = new CreditMinModel();
        }
        return model;
    }


    //提取账户信息
    public static CreditMinModel loadCreditMinByLocal() {
        return getCreditMin(null, CacheType.LOCAL);
    }

    private static void getCreditMinByNet(WCallBack<CreditMinModel> callBack) {
        TopupService topupService = NetworkModule.getRetrofit().create(TopupService.class);
        topupService.getCreditMin(UserInfo.getMemberId())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(resultModel -> {
                    if (resultModel.isSuccess()) {
                        saveCreditMin(resultModel.getData());
                        if (callBack != null) {
                            callBack.callback(resultModel.getData());
                        }
                    }

                }, throwable -> {
                    CrashHelper.postCatchedException(throwable);
                });


    }

    //保存用户充值最低额度信息
    private static void saveCreditMin(CreditMinModel model) {
        int memberId = UserInfo.getMemberId();
        if (memberId > 0 && model != null) {
            String gsonString = JsonUtils.createGsonString(model);
            String key = CREDITMIN + "+" + memberId;
            SharedPreferencesUtils.putData(key, gsonString);
        }
    }

    //-----------与充值额度相关-----------end
    //-----------与充值额度相关-----------end

    //-----------与搜索历史词相关-----------start
    //-----------与搜索历史词相关-----------start

    public static List<String> addSearchKeyword(String keyword) {
        List<String> keywords = new ArrayList<>();
        try {
            //拿到缓存
            String searchList = (String) SharedPreferencesUtils.getData(SEARCH_KEYWORD, "");
            d("--->>>>>>>>---searchList:" + searchList);
            if (!TextUtils.isEmpty(searchList)) {
                String[] split = searchList.split(",");
                if (split != null && split.length > 0) {
                    for (String s : split) {
                        //保持唯一性
                        if (!keywords.contains(s)) {
                            keywords.add(s);
                        }
                    }
                }

            }
            if (!TextUtils.isEmpty(keyword)) {
                //保持唯一性
                Iterator<String> iterator = keywords.iterator();
                while (iterator.hasNext()) {
                    String next = iterator.next();
                    if (TextUtils.equals(next, keyword)) {
                        iterator.remove();
                    }
                }
                keywords.add(keyword);
                String searchList2 = TextUtils.join(",", keywords);
                d("--->>>>>>>>---searchList2:" + searchList2);
                SharedPreferencesUtils.putData(SEARCH_KEYWORD, searchList2);
            }
            Collections.reverse(keywords);
        } catch (Exception e) {
            CrashHelper.postCatchedException(e);
        }
        return keywords;
    }

    public static List<String> clearSearchKeyword() {
        SharedPreferencesUtils.putData(SEARCH_KEYWORD, "");
        return new ArrayList<>();
    }

    //-----------与搜索历史词相关-----------end
    //-----------与搜索历史词相关-----------end

    //-----------与左侧菜单栏相关-----------start
    //-----------与左侧菜单栏相关-----------start

    public static List<CategoryModel> getCategorys(WCallBack<List<CategoryModel>> callBack) {
        List<CategoryModel> list = new ArrayList<>();


        try {
            //从缓存那数据
            String s = (String) SharedPreferencesUtils.getData(CATEGORYS, "");
            Gson gson = new Gson();
            Type type = new TypeToken<List<CategoryModel>>() {
            }.getType();
            List<CategoryModel> categoryModels = gson.fromJson(s, type);
            if (categoryModels != null && categoryModels.size() != 0) {
                list.addAll(categoryModels);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        ApiService apiService = NetworkModule.getRetrofit().create(ApiService.class);
        apiService.getFirstCategorys(LocalManageUtil.getAppLanguage(), null)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ResultModel<List<CategoryModel>>>() {
                    @Override
                    public void accept(ResultModel<List<CategoryModel>> listResultModel) throws Exception {
                        if (listResultModel.isSuccess()) {
                            List<CategoryModel> data = listResultModel.getData();
                            if (data != null) {
                                addMore(data);
                                if (callBack != null) {
                                    callBack.callback(data);
                                }
                                //保存到缓存
                                String gsonString = JsonUtils.createGsonString(data);
                                SharedPreferencesUtils.putData(CATEGORYS, gsonString);
                            }
                        }
                    }
                }, throwable -> CrashHelper.postCatchedException(throwable));

        addMore(list);

        return list;
    }

    private static void addMore(List<CategoryModel> list) {
        boolean isContains = true;//是否含有默认item,2019/12/02移除more
        for (CategoryModel categoryModel : list) {
            if (categoryModel.getSort_order() == -1) {
                isContains = true;
                break;
            }
        }
        if (!isContains) {
            CategoryModel categoryModel = new CategoryModel();
            categoryModel.setCat_name(ResString.get(R.string.more));
            categoryModel.setSort_order(-1);
            list.add(categoryModel);
        } else {//2019/12/02移除more
            for (CategoryModel categoryModel : list) {
                if (categoryModel.getSort_order() == -1) {
                    list.remove(categoryModel);
                    break;
                }
            }
        }
    }

    //-----------与左侧菜单栏相关-----------end
    //-----------与左侧菜单栏相关-----------end

    //-----------与取消订单的原因集合相关-----------start
    //-----------与取消订单的原因集合相关-----------start

    public static void getOrderCancelContents(BaseAppCompatActivity activity, WCallBack<List<OrderCancelModel>> callBack) {
        if (orderCancelModels != null && orderCancelModels.size() != 0) {
            if (callBack != null) {
                callBack.callback(orderCancelModels);
            }
            return;
        }
        ApiService apiService = NetworkModule.getRetrofit().create(ApiService.class);
        Disposable subscribe = apiService.getOrderCancelContents(LocalManageUtil.getAppLanguage())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(disposable -> {
                    if (activity != null) {
                        activity.showLoadingBar(null);
                    }
                })
                .doAfterTerminate(() -> {
                    if (activity != null) {
                        activity.dismissLoadingBar("");
                    }
                })
                .subscribe(listResultModel -> {
                    if (listResultModel.isSuccess()) {
                        List<OrderCancelModel> data = listResultModel.getData();
                        orderCancelModels = data;
                        if (callBack != null) {
                            callBack.callback(data);
                        }
                    }
                }, throwable -> {
                    CrashHelper.postCatchedException(throwable);
                });
        if (activity != null) {
            activity.composite.add(subscribe);
        }
    }

    //-----------与取消订单的原因集合相关-----------end
    //-----------与取消订单的原因集合相关-----------end

}
